/**
 * @将一个正整数转化为其他基数
 *
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @subpackage	default
 */

#include <stdio.h>

#define true 1
#define false 0

//声明函数
int get_int(char *prompt, int lower, int upper);
char *convert_number(int number, int base);

//主函数
int main(int argc, char *argv[]) {
	int number;
	int base;
	char *result;

	do {
		number = get_int("10进制数", 0, 65535);

		// @TODO Segment Fault error to be fixed HERE
		if (number == 0) {
			break;
		}

		base = get_int("目标基数", 2, 16);

		result = convert_number(number, base);

		printf("转换结果：%s\n\n", result);

	} while (true);

	return 0;
}

// get an integer between specified lower and upper limit
int get_int(char *prompt, int lower, int upper) {
	int number;

	do {
		printf("%s: ", prompt);
		scanf("%d", &number);
	} while (number < lower || number > upper);

	return number;
}

//对输入的数字进行处理
char *convert_number(int number, int base) {
	const char numbers[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	
	int digits[64];
	char *result;

	int i = 0;

	do {
		digits[i++] = number % base;
		number = number / base;
	} while (number > 0);

	int j = 0;
	for (--i; i>=0; --i, ++j) {
		result[j] = numbers[digits[i]];
	}

	result[j] = '\0';

	return result;
}

